<template>
  <page-meta :page-style="themeColor"></page-meta>
  <view class="nc-modify-content">
    <view class="modify">
      <view>
        <image v-if="newImg == ''" :src="memberImg ? $util.img(memberImg) : $util.getDefaultImage().head"
          @error="memberImg = $util.getDefaultImage().head" mode="aspectFill"></image>
        <image v-else :src="$util.img(newImg)" @error="newImg = $util.getDefaultImage().head" mode="aspectFill" />

      </view>
    </view>
    <view class="opection-box">
      <block v-if="newImg == ''"><button open-type="chooseAvatar" @chooseavatar="chooseImage">上传头像</button></block>
      <block v-else>
        <view class="opec">
          <button size="mini" type="primary" @click="save()">确认保存</button>
          <button size="mini" open-type="chooseAvatar" @chooseavatar="chooseImage">上传头像</button>
        </view>
      </block>
    </view>

    <img-cropping selWidth="300" selHeight="300" @upload="myUpload" ref="imgCropping"></img-cropping>
    <!-- https://thirdwx.qlogo.cn/mmopen -->
    <loading-cover ref="loadingCover"></loading-cover>
  </view>
</template>

<script>
import imgCropping from '@/components/img-cropping/cropping.vue';

export default {
  data() {
    return {
      memberImg: '',
      newImg: '',
      imgurl: '',
      cooperateId: '',
    };
  },
  components: {
    imgCropping
  },
  onLoad(option) {
    this.cooperateId = option.cooperateId ? option.cooperateId : ''
  },
  onShow() {
    if (!uni.getStorageSync('token')) {
      this.$util.redirectTo(
        '/pages_tool/login/login',
        {
          back: '/pages_tool/member/modify_face'
        },
        'redirectTo'
      );
    }

    this.initGetHeading();
  },
  methods: {
    initGetHeading() {
      this.$api.sendRequest({
        url: '/api/member/info',
        success: res => {
          console.log(res, 'res信息');
          if (res.code == 0) {
            this.$store.commit('setUserInfo', res.data);
            uni.setStorageSync("user_id", res.data.member_id)
            this.memberImg = res.data.headimg;
            this.newImg = res.data.headimg;
          } else {
            this.$util.showToast({
              title: res.message
            });
          }
          if (this.$refs.loadingCover) this.$refs.loadingCover.hide();
        },
        fail: res => {
          if (this.$refs.loadingCover) this.$refs.loadingCover.hide();
        }
      });
    },
    chooseImage(e) {
      uni.showLoading({
        title: '上传中'
      })
      console.log(e, 'e信息');

      let avatar = e.detail.avatarUrl;

      const fileSystemManager = uni.getFileSystemManager();
      fileSystemManager.readFile({
        filePath: avatar,
        encoding: 'base64',
        success: (res) => {
          const base64Data = res.data;
          let tmpAvatarUrl = `data:image/jpeg;base64,${base64Data}`;
          console.log('Base64格式的头像数据:', tmpAvatarUrl);
          this.myUpload({ base64: tmpAvatarUrl })
        },
        fail: (error) => {
          console.error('读取文件失败:', error);
        }
      });


      // const _this = this
      // uni.uploadFile({
      //   url: this.$config.baseUrl + '/api/upload/headimg',
      //   filePath: avatar,
      //   name: 'file',
      //   success: (uploadFileRes) => {
      //     this.memberImg = JSON.parse(uploadFileRes.data).data.pic_path;
      //     this.newImg = JSON.parse(uploadFileRes.data).data.pic_path;
      //     this.imgurl = JSON.parse(uploadFileRes.data).data.pic_path;
      //     uni.hideLoading()
      //   }
      // });



      // this.$refs.imgCropping.fSelect();
    },
    //上传返回图片
    myUpload(rsp) {
      let app_type = 'h5';
      let app_type_name = 'H5';

      // #ifdef MP
      app_type = 'weapp';
      app_type_name = 'weapp';
      // #endif
      uni.request({
        url: this.$config.baseUrl + '/api/upload/headimgBase64',
        method: 'POST',
        data: {
          app_type: app_type,
          app_type_name: app_type_name,
          images: rsp.base64
        },
        header: {
          'content-type': 'application/x-www-form-urlencoded;application/json'
        },
        dataType: 'json',
        responseType: 'text',
        success: res => {
          uni.hideLoading()
          if (res.data.code == 0) {
            this.newImg = res.data.data.pic_path;
            this.imgurl = res.data.data.pic_path;
          }
        },
        fail: () => {
          this.$util.showToast({
            title: '头像上传失败'
          });
        }
      });
    },
    previewImage() {
      uni.previewImage({
        current: 0,
        urls: this.images
      });
    },
    save() {
      this.$api.sendRequest({
        url: '/api/member/modifyheadimg',
        data: {
          headimg: this.imgurl
        },
        success: res => {
          if (res.code == 0) {
            this.$api.sendRequest({
              url: '/api/member/info',
              data: {},
              success: res_ => {
                if (res_.code == 0) {
                  this.$store.commit('setUserInfo', res_.data);
                }
              }
            });

            this.$util.showToast({
              title: '头像修改成功'
            });
            setTimeout(() => {
              // if (this.cooperateId) {
              //   this.$util.redirectTo('/pages_tool/member/info', { cooperateId: this.cooperateId }, 'redirectTo');
              // } else {
              //   this.$util.redirectTo('/pages_tool/member/info', {}, 'redirectTo');
              // }
              if (this.cooperateId) {
                this.$util.redirectTo('/pages_tool/member/info', { cooperateId: this.cooperateId }, 'redirectTo');
              } else {
                // 返回上一级页面
                uni.navigateBack({
                  delta: 1 // 返回的页面数，如果 delta 大于现有页面数，则返回到首页
                });
              }


            }, 2000);
          } else {
            this.$util.showToast({
              title: res.message
            });
          }
        }
      });
    }
  }
};
</script>

<style lang="scss">
page {
  overflow: hidden;
}

.modify {
  position: relative;
  padding-top: 50rpx;

  view {
    width: 500rpx;
    height: 500rpx;
    margin: 0 auto;
    overflow: hidden;
    background-color: #ffffff;
    border: 4rpx solid #ffffff;
    border-radius: 100%;

    image {
      width: 100%;
      height: 100%;
    }
  }
}

.opection-box {
  margin-top: 50rpx;
}

.opec {
  width: 100%;
  padding: 0 10%;
  box-sizing: border-box;
  display: flex;
  justify-content: space-between;
}
</style>
